// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const db = uniCloud.database();
const userDB = db.collection("users");
const { createToken } = require("utils");
const { createUser, getUser, searchUser } = require("./db.js");
const { SuccessModel, ErrorModel } = require("models");

module.exports = {
  _before: function () {
    // 通用预处理器
  },
  async register({ data }) {
    let res;
    res = await searchUser({
      phonenumber: data.phonenumber,
    });
    if (res.err) {
      return new ErrorModel("创建失败！");
    }
    if (res.length > 0) {
      return new ErrorModel("账号已存在！");
    }
    res = await createUser(data);
    if (res.err) {
      return ErrorModel("创建失败！");
    }
    res = await getUser(res.id);
    if (res.err) {
      return new ErrorModel("创建失败！");
    }
    return new SuccessModel(res, "创建成功");
  },
  async login({ data }) {
    const { phonenumber, password } = data;
	console.log(data)
    const res = await searchUser({
      phonenumber,
      password,
    });
    if (res.err) {
      return new ErrorModel("登录失败！");
    }
    const userData = res.length > 0 ? res[0] : null;
    if (!userData) {
      return new ErrorModel("账号或密码错误！");
    }
    delete userData.password;
    const token = createToken({
      id: userData._id,
    });
    return new SuccessModel(
      {
        ...userData,
        token,
      },
      "登录成功"
    );
  },
  async get(id) {
    const res = await getUser(id);
    if (res.err) {
      return new ErrorModel("创建失败！");
    }
    return new SuccessModel(res);
  },
};
